import Mock from 'mockjs'
import store from '../store'
import {
  GetUrlParObj
} from '../utils/common'
import {

  Success,
  Error
} from './response'

const vipTextArr = [
  'VIP尊享满86元减4元运费券（每月3张）',
  'VIP尊享满100元减4元运费券（每月1张）',
  'VIP尊享满24元减4元运费券（每月2张）'
]
const procutArr = ['香蕉', '苹果', '车厘子', '橘子', '橙子'];
//初始化数据
const initShopModel = () => {
  return Mock.mock({
    'list|5-10': [{
      'id|+1': 1,
      name: "@ctitle(7,12)",

      img: require("@/assets/near.png"),
      'sale|1-10': 1,
      'baseprice|5-10': 1,
      'startprice|1-2': 1,
      'yhtext|1': vipTextArr, //从数组 arr 中随机选取 1 个元素，作为最终值。
      items: GetShopItemModel().items
    }]

  })
}
const GetShopItemModel = () => {
  return Mock.mock({
    'items|2-5': [{
      'id|+1': 1,
      'name|1': procutArr,
      'oldprice|50-100': 1,
      'price|1-50.2': 0,
      img: require("@/assets/tomato.png"),
    }]
  })


}
const initCartModel= (shopList) => 
{
    let list=shopList;
    let cartList = [];
  list.forEach((item) => {
    let products = item.items;
    products.forEach((it) => {
      it.ischeck = false;
      it.number = 0;
    })
    cartList.push({
      shopId: item.id,
      shopName: item.name,
      items: products
    })
  })
  return cartList;
  
}


//获取列表
Mock.mock('/api/shop/getlist', 'get', (option) => {

  let shopList = store.state.shop.shopList;
  if (shopList == undefined || shopList.length == 0) {
    //第一次初始化数据
    shopList = initShopModel().list;
    localStorage.shopList = JSON.stringify(shopList);
    store.state.shop.shopList = shopList;

     //添加购物车数据
     let cartList=  initCartModel(shopList);
     localStorage.cartList = JSON.stringify(cartList);
     store.state.shop.cartList = cartList;
  }
  return Success('获取成功', shopList)





})


Mock.mock(RegExp('/api/shop/get' + ".*"), "get", ((options) => {
  // 处理URL根据URL不同返回响应数据
  let obj = GetUrlParObj(options.url);
  if (obj.shopId > 0) {
    let data = store.state.shop.shopList.find((item) => {
      return item.id == obj.shopId;
    })


    return Success('获取成功', data);
  }
  return Error('获取异常');





}));
